package pt.isel.lercm.projectmanager.service;

import java.util.List;
import java.util.Properties;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import pt.isel.lercm.projectmanager.spring.service.IConstanteService;


public class EmailSendService {
	
	private final String mail;
	private final String password;
	private String smtpHost;
	private String smtpPort;
	
	
	public EmailSendService (IConstanteService constanteService){
		mail = constanteService.getValorByName("MAIL_ENDERECO");
		password = constanteService.getValorByName("MAIL_PASSWORD");
		smtpHost = constanteService.getValorByName("MAIL_SMTP_HOST");
		smtpPort = constanteService.getValorByName("MAIL_SMTP_PORT");
	}
	
	public void sendMail(List<String> contactos, String conteudo, String assunto) throws AddressException, MessagingException{
		
		Properties props = new Properties();
		props.put("mail.smtp.host", smtpHost);
		props.put("mail.smtp.socketFactory.port", smtpPort);
		props.put("mail.smtp.socketFactory.class","javax.net.ssl.SSLSocketFactory");
		props.put("mail.smtp.auth", "true");
		props.put("mail.smtp.port", smtpPort);
 
		Session session = Session.getDefaultInstance(props,
			new javax.mail.Authenticator() {
				protected PasswordAuthentication getPasswordAuthentication() {
					return new PasswordAuthentication(mail.split("@")[0], password);
				}
			});
 
		
 
			Message message = new MimeMessage(session);
			
			if (contactos != null && !contactos.isEmpty() && conteudo != null && !conteudo.isEmpty() && assunto != null && !assunto.isEmpty()){
				
				for (String contacto : contactos){
					message.setFrom(new InternetAddress(mail));
					message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(contacto));
					message.setSubject(assunto);
					message.setContent(conteudo, "text/html; charset=utf-8");
					
					Transport.send(message);
					
					//colocar nos logs
					System.out.println("Enviado mail para"+contacto);
				}
				
			}
			
	}
	
}
